<template>
  <div class="love-bg">
    <div class="love-header">
      <span class="back-btn" @click="goHome">← 返回</span>
      <span class="title">AI恋爱大师</span>
      <span class="chat-id">会话ID: {{ chatId.slice(0, 13) }}</span>
    </div>
    <div class="love-chat-card">
      <div class="chat-history" ref="historyRef">
        <div
          v-for="msg in messages"
          :key="msg.id"
          :class="['chat-message', msg.role]"
        >
          <div class="avatar">
            <span v-if="msg.role === 'ai'" class="emoji">❤️</span>
            <span v-else class="emoji user">我</span>
          </div>
          <div class="chat-bubble">
            <span v-for="(line, idx) in msg.content.split(/\n+/)" :key="idx">
              <template v-if="msg.role !== 'user'">　　{{ line }}<br v-if="idx !== msg.content.split(/\n+/).length - 1" /></template>
              <template v-else>{{ line }}<br v-if="idx !== msg.content.split(/\n+/).length - 1" /></template>
            </span>
          </div>
        </div>
      </div>
      <div class="chat-input-bar">
        <input
          v-model="input"
          @keyup.enter="sendMessage"
          placeholder="请输入消息..."
        />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { getMessageList, doChatWithLoveAppSse } from '../api';

function uuidv4() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

const router = useRouter();
const goHome = () => router.push("/");
const SESSION_KEY = 'love_master_chat_id';
let chatId = sessionStorage.getItem(SESSION_KEY);
if (!chatId) {
  chatId = uuidv4();
  sessionStorage.setItem(SESSION_KEY, chatId);
}
const input = ref("");
const messages = ref([]);
const historyRef = ref(null);
let sse = null;

function scrollToBottom() {
  nextTick(() => {
    if (historyRef.value) {
      historyRef.value.scrollTop = historyRef.value.scrollHeight;
    }
  });
}

function sendMessage() {
  const text = input.value.trim();
  if (!text) return;
  messages.value.push({
    id: Date.now() + "-user",
    role: "user",
    content: text,
  });
  input.value = "";
  scrollToBottom();
  if (sse) sse.close();
  sse = doChatWithLoveAppSse(text, chatId);
  let aiMsg = { id: Date.now() + "-ai", role: "ai", content: "" };
  messages.value.push(aiMsg);
  sse.onmessage = (e) => {
    aiMsg.content += e.data;
    messages.value = [...messages.value];
    scrollToBottom();
  };
  sse.onerror = () => {
    sse.close();
  };
}

async function fetchHistory() {
  try {
    const res = await getMessageList(chatId);
    const data = res.data;
    const arr = [];
    if (data.user) {
      data.user.forEach((msg) => {
        arr.push({ role: "user", content: msg });
      });
    }
    if (data.assistant) {
      data.assistant.forEach((msg) => {
        arr.push({ role: "ai", content: msg });
      });
    }
    messages.value = arr;
    scrollToBottom();
  } catch (e) {}
}

onMounted(() => {
  fetchHistory();
  scrollToBottom();
});
</script>

<style scoped>
.love-bg {
  min-height: 100vh;
  background: #fafbfc;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.love-header {
  width: 100vw;
  max-width: 100%;
  background: linear-gradient(90deg, #ffb6c1 0%, #ff6a88 100%);
  color: #fff;
  font-size: 1.2rem;
  font-weight: bold;
  padding: 0.7rem 3vw;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 10;
  border-radius: 0 0 18px 18px;
  box-shadow: 0 2px 12px #ffb6c133;
}
.back-btn {
  cursor: pointer;
  margin-right: 1.5rem;
  color: #fff;
  font-size: 1.1rem;
}
.title {
  flex: 1;
  text-align: center;
  font-size: 1.3rem;
  font-weight: bold;
  letter-spacing: 1px;
}
.chat-id {
  font-size: 0.9rem;
  opacity: 0.8;
}
.love-chat-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 12px #ffb6c122;
  margin: 2rem 0 1rem 0;
  width: 700px;
  max-width: 96vw;
  min-width: 320px;
  display: flex;
  flex-direction: column;
  min-height: 60vh;
  position: relative;
  transition: box-shadow 0.2s;
}
.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem 1.2rem 1rem 1.2rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  min-height: 300px;
}
.chat-message {
  display: flex;
  align-items: flex-end;
  margin-bottom: 0.2rem;
}
.chat-message.user {
  flex-direction: row-reverse;
}
.avatar {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 0.3rem;
}
.emoji {
  font-size: 1.3rem;
  background: #fff0f6;
  border-radius: 50%;
  padding: 0.15rem 0.25rem;
}
.emoji.user {
  background: #1890ff;
  color: #fff;
  font-size: 1rem;
  padding: 0.15rem 0.6rem;
}
.chat-bubble {
  max-width: 80vw;
  min-width: 36px;
  padding: 0.6rem 1rem;
  border-radius: 20px;
  font-size: 0.98rem;
  word-break: break-all;
  box-shadow: 0 1px 4px #eee2;
  line-height: 1.6;
}
.chat-message.user .chat-bubble {
  background: #1890ff;
  color: #fff;
  border-bottom-right-radius: 8px;
}
.chat-message.ai .chat-bubble {
  background: #f5f5f5;
  color: #444;
  border-bottom-left-radius: 8px;
}
.chat-input-bar {
  display: flex;
  padding: 0.7rem 1rem;
  border-top: 1px solid #f0f0f0;
  background: #fff;
  border-radius: 0 0 18px 18px;
  position: sticky;
  bottom: 0;
  z-index: 2;
}
.chat-input-bar input {
  flex: 1;
  padding: 0.6rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
}
.chat-input-bar button {
  margin-left: 0.7rem;
  padding: 0.6rem 1.2rem;
  font-size: 1rem;
  border: none;
  border-radius: 4px;
  background: #ff6a88;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
  box-shadow: 0 1px 4px #ffb6c133;
}
.love-footer {
  width: 100vw;
  min-width: 320px;
  max-width: 100vw;
  text-align: center;
  color: #888;
  font-size: 1rem;
  padding: 1.2rem 0 0.7rem 0;
  display: flex;
  justify-content: center;
  gap: 2rem;
  margin: 0 auto;
}
.footer-link {
  margin-left: 2rem;
  color: #888;
  cursor: pointer;
  font-size: 1rem;
}
.love-footer,
.footer-link,
.love-chat-card,
.chat-bubble {
  word-break: break-all;
}
@media (max-width: 800px) {
  .love-header {
    border-radius: 0;
    padding: 0.7rem 4vw;
    font-size: 1.05rem;
  }
  .title {
    font-size: 1.08rem;
  }
  .love-chat-card {
    width: 100vw;
    max-width: 100vw;
    border-radius: 0;
    margin: 0;
    min-height: 60vh;
    box-shadow: 0 1px 4px #ffb6c122;
  }
  .chat-bubble {
    font-size: 0.92rem;
  }
  .love-footer {
    font-size: 0.9rem;
    padding: 0.7rem 0 0.5rem 0;
    gap: 1rem;
    min-width: 0;
  }
  .footer-link {
    font-size: 0.9rem;
  }
  .chat-input-bar {
    padding: 0.5rem 0.3rem;
  }
}
</style>
